package com.kabuda.blog.common;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * @author kabuda
 * @create 2023-04-03 12:38
 */
public class FileUpDown {
    public static final String FILEPATH = "D:\\cheer\\Java\\项目\\卡布达博客\\img\\";

    public static void main(String[] args) {
    }

    /**
     * 将文件保存到服务器，返回文件路径
     */
    public static String up(MultipartFile img,String folder) {
        String filename = img.getOriginalFilename();
        int i = filename.lastIndexOf(".");
        String suffix = filename.substring(i);
        String prefix = UUID.randomUUID().toString().replace("-", "");
        filename = prefix + suffix;

        try {
            img.transferTo(new File(FILEPATH+folder +"\\"+ filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return filename;
    }

    public static void down(String filename, HttpServletResponse response,String folder) {
        FileInputStream is = null;
        ServletOutputStream os = null;
        try {
            is = new FileInputStream(new File(FILEPATH+folder+"\\"+ filename));
            os = response.getOutputStream();
            response.setContentType("image/jpeg");
            int len;
            byte[] bytes = new byte[1024];
            while ((len = is.read(bytes)) != -1) {
                os.write(bytes, 0, len);
                os.flush();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
